import React from 'react'
import { Toast } from 'antd-mobile';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { actions as userActionCreators } from '../redux/modules/user'
import IScroll from 'iscroll';
import config from '../../config'
import 'antd-mobile/dist/antd-mobile.css'
// 引入common样式
import '../static/css/common.less'

class Main extends React.PureComponent {

  static contextTypes = {
    router: React.PropTypes.object.isRequired
  };

  state = {
    title: '',  
    hasHeader: true,
    searchProps: null
  }

  componentWillReceiveProps(nextProps) {
    // 如果不相等
    if (nextProps.location.pathname != this.props.location.pathname) {
      this.requireAuth(nextProps.location.pathname)
    }
  }

  componentDidMount() {
    // 校验 
    this.requireAuth()
    this.initScroll()
  }

  render() {
    return <div className="page-wrap" id="page-wrap">
      {this.props.children}
    </div>
  }

  // 设置头部内容
  handleInit(config) {
    this.setState({
      ...config
    })

    // 设置头部
    if (config.title) {
      document.title = config.title
    }
  }

  
  requireAuth(pathname) {
    // 是否是首页
    const pages = [`${config.rootAlias}/login`, `${config.rootAlias}/news/detail`, `${config.rootAlias}/forum`]
    const currPath = pathname || this.props.location.pathname

    let isExist = false;

    for(var i = 0; i < pages.length; i++) {
      if (currPath.indexOf(pages[i]) > -1) {
        isExist = true
        break;
      }
    }

    if (!isExist) {
      const token = sessionStorage.getItem('token')
      if (!token) {
        Toast.offline('请先登录', 1)
        setTimeout(() => {
          this.context.router.push(`${config.rootAlias}/login`)
        }, 800)
      }
    }
  }

  initScroll() {
    if (document.getElementById('#page-wrap')) {
      new IScroll('#page-wrap');
    }
  }

}

const stateToProps = state => ({
  ...state.user
})

const dispatchToProps = dispatch => ({
  actions: bindActionCreators(userActionCreators, dispatch)
})

export default connect(stateToProps, dispatchToProps)(Main);
